#include "phdriver_timer.h"
#include "tim.h"

static pphDriver_TimerCallBck_t pTimerIsrCallBack;//回调函数 承接传入的参数！
static volatile uint32_t dwTimerExp;//作为延时调出的标识
static void phDriver_TimerIsrCallBack ( void ) { dwTimerExp = 1;}///回调函数的缺损值

extern TIM_HandleTypeDef htim6;

static void MX_TIM6_Init( phDriver_Timer_Unit_t eTimerUnit, uint32_t dwTimePeriod )
{//MX做的全局接口 屏蔽掉 现在我们在这里封装一成
	TIM_MasterConfigTypeDef sMasterConfig = {0};
	htim6.Instance = TIM6;
	htim6.Init.Prescaler = ( SystemCoreClock / ( eTimerUnit * 1000 ) ) - 1;   
	htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
	htim6.Init.Period = dwTimePeriod * 1000;
	htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;


	if ( HAL_TIM_Base_Init ( &htim6 ) != HAL_OK )
	{
	Error_Handler();
	}
	sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
	sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
	if (HAL_TIMEx_MasterConfigSynchronization(&htim6, &sMasterConfig) != HAL_OK)
	{
	Error_Handler();
	}
}

uint8_t phDriver_TimerStart ( phDriver_Timer_Unit_t eTimerUnit, uint32_t dwTimePeriod, pphDriver_TimerCallBck_t pTimerCallBack )
{

    if ( pTimerCallBack == NULL )/*传入是NULL也就是没有定时回调函数 我们就给它一个缺损函数 就是延时功能！*/
    {
        dwTimerExp = 0;
        pTimerIsrCallBack = phDriver_TimerIsrCallBack;
    }
    else
    {
        pTimerIsrCallBack = pTimerCallBack;
    }
	/*经历上面 pTimerIsrCallBack 这个函数指针一定已经赋值了*/


    MX_TIM6_Init ( eTimerUnit, dwTimePeriod );
    __HAL_TIM_CLEAR_IT ( &htim6, TIM_IT_UPDATE ); 
    HAL_TIM_Base_Start_IT ( &htim6 );

	/*经历上面 我们暴力初始化了TIM*/
    if ( pTimerCallBack == NULL )
    {
        while ( !dwTimerExp );  /* 一直毒蛇延时 */
    }


    return 1;
}

void phDriver_TimerStop ( void )
{
    HAL_TIM_Base_Stop_IT ( &htim6 );
    HAL_TIM_Base_DeInit ( &htim6 );
}



//在main.c找过来的

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM7) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */
	if (htim->Instance == TIM6) {//时间到了怎么办？1关闭定时器2执行回调函数
   	  pTimerIsrCallBack();
	    phDriver_TimerStop();
  }
  /* USER CODE END Callback 1 */
}







/*举例：
延时1S
phDriver_TimerStart(PH_DRIVER_TIMER_SECS,1,NULL);
延时2S
phDriver_TimerStart(PH_DRIVER_TIMER_SECS,2,NULL);
2S以后做一件事
phDriver_TimerStart(PH_DRIVER_TIMER_SECS,2,SHOW);
给OS提供时基
phStatus_t phOsal_StartTickTimer(uint32_t dwTimeMilliSecs)
{
	 phDriver_TimerStart(PH_DRIVER_TIMER_MILLI_SECS, dwTimeMilliSecs, pTickCallBack);
   return PH_OSAL_SUCCESS;
}
static pphDriver_TimerCallBck_t pTickCallBack;
                                pTickCallBack = pTickTimerCallback;

*/
